package cn.xf;

import java.util.*;

/**
 * 实现对hashmap的排序
 */
public class HashMapTest {

    public static void main(String[] args) {
        HashMap<Integer, Child> childs = new HashMap<Integer, Child>();
        childs.put(1, new Child(15, "xiaofu"));
        childs.put(2, new Child(17, "xiaofang"));
        childs.put(3, new Child(16, "xiaohui"));
        System.out.println(childs);
        HashMap<Integer, Child> sortMap = sortMap(childs);
        System.out.println(sortMap);
    }

    private static HashMap<Integer, Child> sortMap(HashMap<Integer, Child> childs) {
        //键集合
        Set<Map.Entry<Integer, Child>> entries = childs.entrySet();
        List<Map.Entry<Integer,Child>> list = new ArrayList<Map.Entry<Integer,Child>>(entries);
        Collections.sort(list, new Comparator<Map.Entry<Integer, Child>>() {
            @Override
            public int compare(Map.Entry<Integer, Child> o1, Map.Entry<Integer, Child> o2) {
                return o2.getValue().getAge()-o1.getValue().getAge();
            }
        });
        LinkedHashMap<Integer,Child> linkedHashMap = new LinkedHashMap<Integer,Child>();
        for(Map.Entry<Integer,Child> entry : list){
            linkedHashMap.put(entry.getKey(),entry.getValue());
        }
        return  linkedHashMap;
    }
}
